<template>
  <el-container class="container">
    <el-header class="header">
      <el-menu mode="horizontal" :router="true">
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/tiktokreport">生成抖音报告</el-menu-item>
        <el-menu-item index="/mtreport">生成美团报告</el-menu-item>
      </el-menu>
      <div class="download-container" v-if="!isHomePage">
        <button class="download-button" @click="downloadReport">
          下载完整PDF报告
        </button>
        <button class="preview-button" @click="previewReportAsImage">
          预览报告图片
        </button>
      </div>
    </el-header>
    <div class="main">
      <router-view></router-view>
      <div class="version-info">版本号：V1.1.3</div>
    </div>
  </el-container>

  <!-- 报告图片预览弹窗 -->
  <el-dialog v-model="dialogVisible" title="报告预览" width="90%" :before-close="handleDialogClose">
    <div class="report-preview-container">
      <img v-if="reportImageUrl" :src="reportImageUrl" class="report-preview-image" />
      <div v-else class="loading-message">正在生成预览图片，请稍候...</div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="downloadImage">保存图片</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import html2pdf from 'html2pdf.js'
import html2canvas from 'html2canvas'
import { useRoute } from 'vue-router'
import { computed, ref } from 'vue'

// 获取当前路由
const route = useRoute()

// 计算属性判断是否为首页
const isHomePage = computed(() => {
  return route.path === '/' || route.path === ''
})

// 预览弹窗相关状态
const dialogVisible = ref(false)
const reportImageUrl = ref('')

// 处理弹窗关闭
const handleDialogClose = (done: () => void) => {
  reportImageUrl.value = ''
  done()
}

// 下载图片
const downloadImage = () => {
  if (!reportImageUrl.value) {
    ElMessage.warning('图片尚未生成完成，请稍候')
    return
  }

  const link = document.createElement('a')
  link.href = reportImageUrl.value
  link.download = '抖音报告.png'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('图片已保存')
}

// 将报告转为高质量图片并显示在弹窗中
const previewReportAsImage = async () => {
  try {
    // 等待较长时间确保内容完全渲染（包括所有图表和图片）
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 查找报告容器
    const possibleSelectors = [
      '.report-containers', // TiktokReportTemplate类名
      '#report-container',  // 可能使用的ID
      '.report-container',  // 可能使用的类名
      '.container'          // 备用容器
    ]

    let element = null
    for (const selector of possibleSelectors) {
      const el = document.querySelector(selector)
      if (el) {
        element = el as HTMLElement
        console.log(`找到报告容器: ${selector}`)
        break
      }
    }

    if (!element) {
      ElMessage.error('未找到报告内容，请确保报告已加载')
      return
    }

    // 显示弹窗并设置加载状态
    dialogVisible.value = true
    reportImageUrl.value = ''

    // 创建高质量图片
    const canvas = await html2canvas(element, {
      scale: 2, // 设置为2倍大小，提高清晰度
      useCORS: true, // 允许加载跨域图片
      logging: true,
      allowTaint: true,
      backgroundColor: "#ffffff"
    })

    // 转换为图片URL
    const imageUrl = canvas.toDataURL('image/png', 1.0)
    reportImageUrl.value = imageUrl

    ElMessage.success('报告图片生成成功')
  } catch (error: any) {
    console.error('生成图片失败:', error)
    ElMessage.error(`生成图片失败: ${error.message}`)
  }
}

const downloadReport = async () => {
  try {
    // 等待较长时间确保内容完全渲染（包括所有图表和图片）
    await new Promise(resolve => setTimeout(resolve, 2000));

    // 查找报告容器
    const possibleSelectors = [
      '.report-containers', // TiktokReportTemplate类名
      '#report-container',  // 可能使用的ID
      '.report-container',  // 可能使用的类名
      '.container'          // 备用容器
    ];

    let element = null;
    for (const selector of possibleSelectors) {
      const el = document.querySelector(selector);
      if (el) {
        element = el as HTMLElement;
        console.log(`找到报告容器: ${selector}`);
        break;
      }
    }

    if (!element) {
      ElMessage.error('未找到报告内容，请确保报告已加载');
      return;
    }

    // 添加页码容器
    const pageNumberContainer = document.createElement('div');
    pageNumberContainer.style.cssText = `
      position: fixed;
      bottom: 10mm;
      right: 10mm;
      font-size: 10px;
      color: #666;
      z-index: 1000;
    `;
    pageNumberContainer.className = 'page-number';
    pageNumberContainer.innerHTML = '<span class="pageNumber"></span> / <span class="totalPages"></span>';
    document.body.appendChild(pageNumberContainer);

    // 定义A4尺寸（以mm为单位）
    const a4Width = 210; // A4宽度为210mm
    const a4Height = 297; // A4高度为297mm

    // 配置PDF生成选项
    const opt = {
      margin: [10, 10, 15, 10], // 上、右、下、左边距（单位：mm）
      filename: '抖音报告.pdf',
      image: { type: 'jpeg', quality: 0.95 },
      html2canvas: {
        scale: 2,
        useCORS: true,
        logging: true,
        allowTaint: true,
      },
      jsPDF: {
        unit: 'mm',
        format: 'a4',
        orientation: 'portrait',
        compress: true,
        // 添加页码函数
        putTotalPages: true,
        addPage: function (pdf: any, pageNumber: number, totalPages: number) {
          pdf.setFontSize(10);
          pdf.setTextColor(102, 102, 102);
          pdf.text(
            `${pageNumber} / ${totalPages}`,
            pdf.internal.pageSize.getWidth() - 20,
            pdf.internal.pageSize.getHeight() - 10
          );
        }
      },
      pagebreak: {
        mode: ['avoid-all', 'css', 'legacy'],
        before: '.page-break-before',
        after: '.page-break-after',
        avoid: ['.card-container', '.el-card', '.analysis-card']
      }
    };

    // 显示加载提示
    ElMessage.info('正在生成PDF文件，请稍候...');
    console.log('开始生成PDF，元素:', element);

    // 尝试移除可能导致问题的样式限制
    document.body.style.overflow = 'visible';
    document.documentElement.style.overflow = 'visible';

    // 获取内容尺寸以设置PDF大小
    const width = element.offsetWidth;
    const height = element.offsetHeight;
    console.log(`内容尺寸: ${width}px x ${height}px`);

    // 生成PDF
    await html2pdf()
      .set(opt)
      .from(element)
      .save()
      .then(() => {
        console.log('PDF生成完成');
        ElMessage.success('PDF文件生成成功');
      })
      .catch((error: any) => {
        console.error('PDF生成失败:', error);
        ElMessage.error(`生成PDF失败: ${error.message}`);
      });

    // 移除页码容器
    document.body.removeChild(pageNumberContainer);

    // 恢复样式
    document.body.style.overflow = '';
    document.documentElement.style.overflow = '';

  } catch (error: any) {
    console.error('生成PDF失败:', error);
    ElMessage.error(`生成PDF失败: ${error.message}`);

    // 提供更多调试信息
    console.log('DOM信息:');
    console.log('- Body子元素数量:', document.body.children.length);
    const reportElement = document.querySelector('.report-containers') || document.getElementById('report-container');
    if (reportElement) {
      console.log('- 报告容器可见性:', getComputedStyle(reportElement).display);
      console.log('- 报告容器高度:', getComputedStyle(reportElement).height);
      console.log('- 报告容器子元素数量:', reportElement.children.length);
    } else {
      console.log('- 未找到报告容器');
    }
  }
};

</script>
<style>
.el-header {
  padding: 0;
}

.version-info {
  font-size: 12px;
  color: #666;
  text-align: center;
  margin-top: 10px;
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  background-color: #fff;
  padding: 5px 0;
}

.main {
  height: calc(100vh - 100px);
  overflow: hidden;
  margin-top: 60px;
  display: block;
  width: 100%;
}

.header {
  background-color: #fff;
  color: #fff;
  position: fixed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  z-index: 1000;
  top: 0;
  left: 0;
  height: 60px;
}

.container {
  width: 100vw;
}

/* 下载按钮样式 */
.download-container {
  display: flex;
  justify-content: center;
  margin: 30px 20px;

}

.download-button {
  background: linear-gradient(135deg, #6366F1, #9333EA);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.download-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.15);
}

.download-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 防止卡片跨页的样式 */
.el-card,
.card-container,
.analysis-card {
  break-inside: avoid;
  page-break-inside: avoid;
  margin-bottom: 30px;
  /* 增加卡片之间的间距 */
  margin-top: 20px;
  /* 增加卡片顶部间距 */
  padding-top: 10px;
  /* 增加内部顶部填充 */
}

/* 确保每个卡片容器都是一个独立的打印单元 */
.report-containers>div,
.report-container>div {
  break-inside: avoid-page;
  page-break-inside: avoid;
  margin-top: 15px;
  /* 添加容器顶部间距 */
  padding-top: 10px;
  /* 添加容器内部顶部填充 */
}

/* 针对第一个卡片的特殊处理 */
.report-containers>div:first-child,
.report-container>div:first-child {}

/* 预览按钮样式 */
.preview-button {
  background: linear-gradient(135deg, #4ade80, #22c55e);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  margin-left: 10px;
}

.preview-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.15);
}

.preview-button:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 报告图片预览样式 */
.report-preview-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  overflow-y: auto;
  max-height: 70vh;
  padding: 20px 0;
}

.report-preview-image {
  max-width: 100%;
  height: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 修复el-dialog内容区域的样式 */
:deep(.el-dialog__body) {
  padding: 0;
  overflow: hidden;
}

.loading-message {
  padding: 20px;
  text-align: center;
  font-size: 16px;
  color: #666;
}

.el-dialog__title {
  font-weight: bold;
  font-size: 24px;
}

.version-info {
  font-size: 12px;
  color: #666;
  text-align: center;
}
</style>
